package com.example.testone.utils

import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbManager
import android.util.Log
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.hoho.android.usbserial.driver.UsbSerialDriver
import com.hoho.android.usbserial.driver.UsbSerialPort
import com.hoho.android.usbserial.driver.UsbSerialProber
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class UsbPermission @Inject constructor(@ApplicationContext val context: Context) {

    companion object{
        const val TAG = "UsbPermission"
        const val ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    }

    val manager:UsbManager by lazy {
        context.getSystemService(Context.USB_SERVICE) as UsbManager
    }

    val availableDrivers:List<UsbSerialDriver> by lazy {
        UsbSerialProber.getDefaultProber().findAllDrivers(manager);
    }

    var driver:UsbSerialDriver? = null
    var connection: UsbDeviceConnection?=null
    var usbSerialPort: UsbSerialPort?=null

    val mUsbPermissionActionReceiver =object : BroadcastReceiver(){

        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action
            Log.e(TAG, "-----mUsbPermissionActionReceiver---${action}")
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    val usbDevice: UsbDevice? = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        //user choose YES for your previously popup window asking for grant perssion for this usb device
                        if(null != usbDevice){
                            afterGetUsbPermission(usbDevice);
                        }
                    }
                    else {
                        //user choose NO for your previously popup window asking for grant perssion for this usb device
                        Toast.makeText(context, "Permission denied for device:${usbDevice}", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }

    }

    private fun afterGetUsbPermission(usbDevice: UsbDevice) {
        doYourOpenUsbDevice(usbDevice);
    }

    private fun doYourOpenUsbDevice(usbDevice: UsbDevice) {
        if(availableDrivers.isEmpty()){
            return
        }
        driver = availableDrivers.get(0)
        connection  = manager.openDevice(driver!!.getDevice())
        usbSerialPort = driver!!.ports.get(0)
    }

    init {
        Log.e(TAG,  "availableDrivers-size=${availableDrivers.size};")
        regUsbPermissionListener();
        openUsbDevice()
    }

    fun openUsbDevice()
    {

        val manager = ContextCompat.getSystemService(context, UsbManager::class.java) as UsbManager

        val availableDrivers: List<UsbSerialDriver> =
            UsbSerialProber.getDefaultProber().findAllDrivers(
                manager
            )
        if (availableDrivers.isEmpty()) {
            return
        }
//        Log.e(TAG,  "availableDrivers-size=${availableDrivers.size};")
        // Open a connection to the first available driver.
        val driver: UsbSerialDriver = availableDrivers[0]
        val mPermissionIntent =
            PendingIntent.getBroadcast(context, 0, Intent(ACTION_USB_PERMISSION), 0)
//        manager.requestPermission(driver.getDevice(), mPermissionIntent);
        for (usbDevice in manager.deviceList.values){
            if(manager.hasPermission(usbDevice)){
                afterGetUsbPermission(usbDevice);
            }else{
                manager.requestPermission(usbDevice, mPermissionIntent);
            }

        }
    }

    private fun regUsbPermissionListener() {
        val filter = IntentFilter(ACTION_USB_PERMISSION)
        context.registerReceiver(mUsbPermissionActionReceiver,filter)

    }
}